<template>
	<div id="wangeditor" ref="editorElem" class="editor"></div>
</template>

<script>
	import E from 'wangeditor';
	export default {
		props: {
			editorId: {
				type: Number,
				default: 0
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			disabled: {
				handler(newVal) {
					if (this.editor) {
						if (newVal) {
							this.editor.disable();
						} else {
							this.editor.enable();
						}
					}
				},
				immediate: true,
			}
		},
		data() {
			return {
				editor: null
			};
		},
		methods: {
			setContent(res) {
				this.editor.txt.html(res);
			}
		},
		mounted() {
			let $this = this;

			this.editor = new E(this.$refs.editorElem);

			// 编辑器的事件，每次改变会获取其html内容
			this.editor.config.onchange = html => {
				this.$emit('editorChange', html, this.editorId);
			};

			//高度
			this.editor.config.height = 500;

			// zindx
			this.editor.config.zIndex = 1500;

			// focus
			this.editor.config.focus = false;

			// 全屏
			this.editor.config.showFullScreen = false;

			// placeholder
			this.editor.config.placeholder = '请输入';

			this.editor.config.customUploadImg = async (files, insert) => {
				// files 是 input 中选中的文件列表
				// insert 是获取图片 url 后，插入到编辑器的方法
				for (var i = 0; i < files.length; i++) {
					let res = await uniCloud.uploadFile({
						filePath: window.URL.createObjectURL(files[i]),
						cloudPath: files[i].name
					});

					// 上传代码返回结果之后，将图片插入到编辑器中
					let url = res.fileID;
					if (url.indexOf('cloud://') !== -1) {
						const urls = await uniCloud.getTempFileURL({
							fileList: [url]
						});
						if (urls.fileList && urls.fileList.length > 0) {
							url = urls.fileList[0].tempFileURL || '';
						}
					}

					insert(url);
				}
			};
			this.editor.create(); // 创建富文本实例
			this.$emit('created', this.editor);
		}
	};
</script>

<style></style>
